#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

int flgthread = 1;
sem_t isKey,isCal;
int fd;
int count=0;
char buffer[]="Hello,young man!\r\n";
char buffer2[]="Hello2!\r\n";

void *trd_func(void)
{
	while(1)
	{

		printf("Begin to read uart.\n");

		count=read(fd,buffer,10);
        if(count>0)
        {
			flgthread=0;
            buffer[count]=0;
            printf("收到数据:%s\r\n",buffer);

        }
			flgthread=1;		


	}
}
int main()
{

//uart
	struct termios uart_cfg;
	fd=open("/dev/ttyS0",O_RDWR|O_NONBLOCK|O_NOCTTY);
	if(fd<0)
	{
		perror("Failed to open serial:");
		return -1;
	}
    fcntl(fd,F_SETFL,0);
	cfmakeraw(&uart_cfg);
	cfsetspeed(&uart_cfg,B115200);	
    uart_cfg.c_cflag|=CLOCAL|CREAD;
	tcflush(fd,TCIOFLUSH);
	tcsetattr(fd,TCSANOW,&uart_cfg);
	
//thread
	pthread_t tid;
	int arg[2];
	sem_init(&isKey,0,1);
	sem_init(&isCal,0,0);
	pthread_create(&tid,NULL,trd_func,NULL );
	





	while(1)
	{
		printf("Begin to write uart.\n");
		if (flgthread==1)
		{
			write(fd,buffer2,strlen(buffer2));		
		}
		sleep(2);

		
	}

	return 0;
}
